<template>
  <div class="main-container">
    <div class="left_container">
      <div class="search_container">
        <div class="search_item">
          <div class="name">客户名称</div>
          <div class="input">
            <el-input v-model="pageData.customerName" clearable @clear="getList" />
          </div>
        </div>
        <div class="search_item">
          <div class="name">拜访时间</div>
          <div class="input">
            <TimeRangeSearch :band-value.sync="pageData.searchTime" @clearData="getList" />
          </div>
        </div>
        <div class="search_item">
          <div class="name" />
          <div class="input">
            <el-button type="search" @click.stop="getList">搜索</el-button>
          </div>
        </div>
        <div class="search_item">
          <div class="name">拜访人员</div>
          <div class="input">
            <el-select v-model="pageData.visitorId" filterable clearable>
              <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.realName"
                :value="item.userId"
              />
            </el-select>
          </div>
        </div>
        <div class="search_item">
          <div class="name">拜访方式</div>
          <div class="input">
            <DictSelect
              :band-value.sync="pageData.visitType"
              dict-type="visitType"
            />
          </div>
        </div>
        <div class="search_item">
          <div class="name">下次拜访时间</div>
          <div class="input">
            <TimeRangeSearch :band-value.sync="pageData.searchTime2" @clearData="getList" />
          </div>
        </div>
      </div>
      <div ref="middle_container" class="middle_container">
        <el-table
          ref="table"
          :data="tableData"
          stripe
          border
          :height="tableHeight"
          style="width: 99.9%"
          highlight-current-row
          :cell-style="cellStyle"
          @row-click="rowClick"
        >
          <el-table-column type="selection" width="70" />
          <el-table-column prop="customerName" label="客户名称" min-width="150" />
          <el-table-column prop="channelName" label="渠道名称" min-width="150" />
          <el-table-column prop="visitTime" min-width="150" label="拜访时间" />
          <el-table-column prop="visitorName" label="拜访人员" />
          <el-table-column prop="visitType" label="拜访方式" />
          <el-table-column prop="visitResult" label="拜访结果" />
          <el-table-column prop="visitContent" label="拜访内容" min-width="250" />

          <el-table-column prop="demand" label="需求" min-width="150" />
          <el-table-column prop="businessOpportunity" label="商机" min-width="150" />
          <el-table-column prop="participator" min-width="150" label="本次其他参与人" />
          <!-- <el-table-column prop="attaUrl" label="附件" /> -->
          <!-- <el-table-column label="附件" show-overflow-tooltip>
            <template slot-scope="scope">
              <a :href="scope.row.attaUrl" target="_blank" class="buttonText">{{
                scope.row.fileName
              }}</a>
            </template>
          </el-table-column> -->
          <el-table-column
            label="附件"
            prop="fileName"
            width="170"
          >
            <template slot-scope="scope">
              <FileManage
                v-if="scope.row.fileName"
                :readonly="true"
                :file-names.sync="scope.row.fileName"
                :file-real-names.sync="scope.row.fileRealName"
              />
            </template>
          </el-table-column>
          <el-table-column prop="visitNextTime" min-width="150" label="下次拜访时间" />
          <el-table-column prop="participatorNext" min-width="150" label="下次其他参与人" />

          <infinite-loading
            ref="infiniteLoading"
            slot="append"
            force-use-infinite-wrapper=".el-table__body-wrapper"
            @infinite="loadNext"
          />
        </el-table>
      </div>
      <div class="button_container">
        <el-button type="add" @click.stop="add">新增</el-button>
        <RemoveButton :page="this" />
      </div>
    </div>
    <div class="right_container">
      <div class="header_container">
        编辑拜访跟进
      </div>
      <div class="add_container">
        <div class="add_item first">
          <div class="name"><label class="bitian">*</label>客户名称</div>
          <div v-if="isEdit" class="input">
            <CustomerModelingSelect
              :band-value.sync="addData"
              show-prop="customerName"
            />
          </div>
          <div v-else class="show">{{ addData.customerName }}</div>
        </div>
        <div class="add_item">
          <div class="name"><label class="bitian">*</label>拜访时间</div>
          <div v-if="isEdit" class="input">
            <el-date-picker
              v-model="addData.visitTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              placeholder="请选择"
              :editable="false"
            />
          </div>
          <div v-else class="show">{{ addData.visitTime }}</div>
        </div>
        <div class="add_item">
          <div class="name"><label class="bitian">*</label>拜访人员</div>
          <div v-if="isEdit" class="input">
            <el-select v-model="addData.visitorId" filterable clearable>
              <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="item.realName"
                :value="item.userId"
              />
            </el-select>
          </div>
          <div v-else class="show">{{ addData.visitorName }}</div>
        </div>

        <div class="add_item">
          <div class="name"><label class="bitian">*</label>拜访方式</div>
          <div v-if="isEdit" class="input">
            <div class="input">
              <DictSelect
                :band-value.sync="addData.visitTypeId"
                dict-type="visitType"
              />
            </div>
          </div>
          <div v-else class="show">{{ addData.visitType }}</div>
        </div>

        <div class="add_item">
          <div class="name"><label class="bitian">*</label>拜访结果</div>
          <div v-if="isEdit" class="input">
            <div class="input">
              <DictSelect
                :band-value.sync="addData.visitResultsId"
                dict-type="visitResultType"
              />
            </div>
          </div>
          <div v-else class="show">{{ addData.visitResult }}</div>
        </div>

        <div class="add_item">
          <div class="name">拜访内容</div>
          <div v-if="isEdit" class="input">
            <el-input
              v-model="addData.visitContent"
              clearable
              placeholder="请填写"
            />
          </div>
          <div v-else class="show">{{ addData.visitContent }}</div>
        </div>

        <div class="add_item">
          <div class="name">需求</div>
          <div v-if="isEdit" class="input">
            <el-input v-model="addData.demand" clearable placeholder="请填写" />
          </div>
          <div v-else class="show">{{ addData.demand }}</div>
        </div>

        <div class="add_item">
          <div class="name">商机</div>
          <div v-if="isEdit" class="input">
            <el-input
              v-model="addData.businessOpportunity"
              clearable
              placeholder="请填写"
            />
          </div>
          <div v-else class="show">{{ addData.businessOpportunity }}</div>
        </div>
        <div class="add_item">
          <div class="name">本次其他参与人</div>
          <div v-if="isEdit" class="input">
            <el-select
              v-model="addData.participatorIds2"
              filterable
              clearable
              multiple
            >
              <el-option
                v-for="item in userOptions"
                :key="item.userId+''"
                :label="item.realName"
                :value="item.userId+''"
              />
            </el-select>
          </div>
          <div v-else class="show">{{ addData.participator }}</div>
        </div>

        <div class="add_item">
          <div class="name">附件</div>
          <div class="input">
            <FileManage
              :readonly="!isEdit"
              :file-names.sync="addData.fileName"
              :file-real-names.sync="addData.fileRealName"
              style="padding-left: 20px"
              @fileName="setFileName"
            />
          </div>
        </div>
        <div class="add_item">
          <div class="name">下次拜访时间</div>
          <div v-if="isEdit" class="input">
            <el-date-picker
              v-model="addData.visitNextTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
              placeholder="请选择"
              :editable="false"
            />
          </div>
          <div v-else class="show">{{ addData.visitNextTime }}</div>
        </div>

        <div class="add_item">
          <div class="name">下次其他参与人</div>
          <div v-if="isEdit" class="input">
            <el-select
              v-model="addData.participatorNextIds2"
              filterable
              clearable
              multiple
            >
              <el-option
                v-for="item in userOptions"
                :key="item.userId+''"
                :label="item.realName"
                :value="item.userId+''"
              />
            </el-select>
          </div>
          <div v-else class="show">{{ addData.participatorNext }}</div>
        </div>
      </div>
      <div class="button_container">
        <el-button v-if="isEdit" type="save" @click.stop="save">保存</el-button>
        <el-button v-else type="edit" @click.stop="edit">编辑</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { list, addOrUpdate, remove, getInfo, getInfo2 } from '@/api/sale/visitsFollowup'
import { list as getUser } from '@/api/system/user'
import { mapGetters } from 'vuex'
// import user from '@/store/modules/user'
export default {
  name: 'Index',
  computed: {
    ...mapGetters(['userId', 'userName']),
    notificationId: {
      get: function() {
        return this.$store.state.notification.notificationId
      },
      set: function(newValue) {
        this.$store.state.notification.notificationId = newValue
      }
    }
  },
  watch: {
    'pageData.visitType'(value) {
      if (value == '' || value == undefined) {
        this.getList()
      }
    },
    'pageData.visitorId'(value) {
      if (value == '' || value == undefined) {
        this.getList()
      }
    },
    'addData.participatorIds2'() {
      if (!this.triggerTag) {
        return
      }
      if (this.addData.participatorIds2 == '--' || this.addData.participatorIds2 == '' || this.addData.participatorIds2 == undefined) {
        this.addData.participatorIds = ''
      } else {
        this.addData.participatorIds = this.addData.participatorIds2.join(',')
        const cacheName = []
        this.addData.participatorIds2.forEach(item => {
          cacheName.push((this.userOptions.filter(item2 => item2.userId + '' == item))[0].realName)
        })
        this.addData.participator = cacheName.join(',')
      }
    },
    'addData.participatorNextIds2'() {
      if (!this.triggerTag) {
        return
      }
      if (this.addData.participatorNextIds2 == '--' || this.addData.participatorNextIds2 == '' || this.addData.participatorNextIds2 == undefined) {
        this.addData.participatorNextIds = ''
      } else {
        this.addData.participatorNextIds = this.addData.participatorNextIds2.join(',')
        const cacheName = []
        this.addData.participatorNextIds2.forEach(item => {
          cacheName.push((this.userOptions.filter(item2 => item2.userId + '' == item))[0].realName)
        })
        this.addData.participatorNext = cacheName.join(',')
      }
    }
  },
  beforeDestroy() {
    this.notificationId = 0
  },
  data() {
    return {
      pageData: {
        customerName: undefined,
        searchTime: undefined,
        searchTime2: undefined,
        visitorId: undefined,
        visitType: undefined,
        pageNum: 1,
        pageSize: 15,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      addData: {
        id: '--',
        customerId: '--',
        customerName: '--',
        visitTime: '--',
        visitNextTime: '--',
        visitorId: '--',
        visitorName: '--',
        visitTypeId: '--',
        visitType: '--',
        visitResultsId: '--',
        visitResult: '--',
        visitContent: '--',
        demand: '--',
        participator: '--',
        participatorIds: '--',
        participatorIds2: '--',
        businessOpportunity: '--',
        participatorNext: '--',
        participatorNextIds: '--',
        participatorNextIds2: '--',
        fileName: '',
        fileRealName: ''
      },
      mainId: 'id',
      tableHeight: '0',
      tableData: [],
      // tableHeight2: '300',
      // tableData2: [],
      userOptions: [],
      triggerTag: false, // 触发标志，watch是否触发
      isEdit: false // false:右侧区域仅为展示,true:右侧区域可编辑
    }
  },
  mounted() {
    this.getUser()
    this.$nextTick(() => {
      this.tableHeight = this.$refs.middle_container.offsetHeight
    })
  },
  methods: {
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property == 'fileName') {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
    },
    rowClick(row, column, event) {
      // 单击行选中
      this.triggerTag = false
      this.getInfo(row)
    },

    getList() {
      // 获取数据
      this.pageData.pageNum = 1
      this.tableData = []
      this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset')
    },
    loadNext($state) {
      // 加载下一页数据
      list(this.pageData).then(res => {
        if (res.data.length > 0) {
          this.tableData = this.tableData.concat(res.data)
          this.pageData.pageNum++
          // 如果是从消息通知界面点过来的，设置notificationId未点击状态，模拟单机行
          if (this.notificationId) {
            const selectedRow = this.tableData.filter(item => item.customerName == this.notificationId)
            if (selectedRow && selectedRow.length > 0) {
              this.$refs.table.setCurrentRow(selectedRow[0])
              // 模拟点击行
              this.rowClick(selectedRow[0])
              this.notificationId = 0
            }
          }
          $state.loaded()
        } else {
          $state.complete()
        }
      })
    },
    add() {
      // 新增按钮
      this.$refs.table.setCurrentRow(-1) // 清除高亮
      Object.keys(this.addData).forEach(key => {
        // 清空右边数据
        this.addData[key] = ''
      })
      this.addData.visitorId = JSON.parse(JSON.stringify(this.userId))
      this.triggerTag = true
      this.isEdit = true // 右边输入框显示出来
    },
    edit() {
      // 编辑按钮
      if (this.addData[this.mainId] == '--') {
        this.$message({
          message: '请先选择要操作的数据',
          type: 'warning'
        })
      } else {
        this.triggerTag = true
        this.isEdit = true // 右边输入框显示出来
      }
    },
    checkForm() {
      if (!this.addData.customerName) {
        this.$message({
          message: '请输入客户名称',
          type: 'warning'
        })
        return false
      }
      if (!this.addData.visitTime) {
        this.$message({
          message: '请选择拜访时间',
          type: 'warning'
        })
        return false
      }
      if (!this.addData.visitorId) {
        this.$message({
          message: '请选择拜访人员',
          type: 'warning'
        })
        return false
      }
      return true
    },
    save() {
      // 保存按钮
      if (this.checkForm()) {
        const cacheData = JSON.parse(JSON.stringify(this.addData))
        addOrUpdate(cacheData).then(res => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.getList()
          if (!this.addData[this.mainId]) {
            // 新增
            Object.keys(this.addData).forEach(key => {
              // 清空右边数据
              this.addData[key] = ''
            })
          } else {
            // 编辑
            this.getInfo2(cacheData)
          }
        })
      }
    },
    // 当前页的删除接口
    doRemove(data) {
      Object.keys(this.addData).forEach(key => {
        // 给右边数据赋值
        this.addData[key] = '--'
      })
      this.isEdit = false // 右边输入框隐藏
      return remove(data)
    },
    getInfo(row) {
      // 获取右侧数据
      getInfo(row[this.mainId]).then(res => {
        Object.keys(this.addData).forEach(key => {
          // 给右边数据赋值
          this.addData[key] = res.data[key] || ''
        })
        if (this.addData.participatorIds) {
          this.addData.participatorIds2 = this.addData.participatorIds.split(',')
        }
        if (this.addData.participatorNextIds) {
          this.addData.participatorNextIds2 = this.addData.participatorNextIds.split(',')
        }
      })
      this.isEdit = false // 右边输入框隐藏
    },
    getInfo2(row) {
      // 获取右侧数据
      getInfo2(row[this.mainId]).then(res => {
        Object.keys(this.addData).forEach(key => {
          // 给右边数据赋值
          this.addData[key] = res.data[key] || ''
        })
        if (this.addData.participatorIds) {
          this.addData.participatorIds2 = this.addData.participatorIds.split(',')
        }
        if (this.addData.participatorNextIds) {
          this.addData.participatorNextIds2 = this.addData.participatorNextIds.split(',')
        }
      })
      this.isEdit = false // 右边输入框隐藏
    },
    getUser() {
      // 获取右侧数据
      getUser().then(res => {
        this.userOptions = res.data
      })
    },
    setFileName(...data) {
      this.addData.fileName = data[0]
      this.addData.fileRealName = data[1]
    }
  }
}
</script>

<style lang="less" scoped>
.main-container {
  .left_container {
    width: 60%;
    .search_container {
      .search_item {
        .name {
          width: 100px;
        }
      }
    }
  }
  .right_container {
    .add_container {
      .add_item {
        .name {
          width: 120px;
        }
      }
    }
  }
}
</style>
